package com.spark.httpspost;

import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) throws IOException {
        BasicCookieStore cookieStore;
//整个过程用一个client
        CloseableHttpClient httpclient;
        cookieStore = new BasicCookieStore();
        httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
//先访问一下首页，然后cookie、会填充进来
        HttpGet httpget = new HttpGet("https://leaver.me/index.htm");
        httpclient.execute(httpget);
        CloseableHttpResponse responseCookie = null;
//然后post请求登陆
        HttpPost httpost = new HttpPost("https://leaver.me/login.htm");
        System.setProperty("javax.net.ssl.trustStore", "证书路径");
//通过键值对来作为post参数
        List<NameValuePair> nameValuePairs = new ArrayList<>(1);
        nameValuePairs.add(new BasicNameValuePair("loginType", "1"));
        nameValuePairs.add(new BasicNameValuePair("loginName", "admin"));
        nameValuePairs.add(new BasicNameValuePair("Password", "123456"));
        httpost.setEntity(new UrlEncodedFormEntity(nameValuePairs, Consts.UTF_8));
        CloseableHttpResponse responLogin = httpclient.execute(httpost);
        System.out.println(responLogin.getStatusLine());
        responLogin.getEntity().writeTo(System.out);
    }
}
